<template>
  <el-breadcrumb :separator-icon="ArrowRight">
    <el-breadcrumb-item :to="{ path: '/' }">Home</el-breadcrumb-item>
    <el-breadcrumb-item>商品管理</el-breadcrumb-item>
    <el-breadcrumb-item>添加商品</el-breadcrumb-item>
  </el-breadcrumb>

  <el-card class="box-card">
    <el-alert title="下面输入添加商品的信息" type="info" center show-icon style="margin-bottom: 10px"/>
    <el-steps :active="active" finish-status="success" align-center>
      <el-step title="基本信息"/>
      <el-step title="商品静态属性"/>
      <el-step title="商品动态属性"/>
      <el-step title="商品图片"/>
      <el-step title="商品内容"/>
      <el-step title="完成"/>
    </el-steps>

    <el-tabs tab-position="left" class="el-tabs" v-model="active" :before-leave="beforeLeave">
      <el-form :model="addForm" ref="addFormRef" :rules="addFormRules">
        <el-tab-pane label="基本信息" :name="0">
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="addForm.name"></el-input>
          </el-form-item>
          <el-form-item label="商品价格" prop="price">
            <el-input v-model="addForm.price"></el-input>
          </el-form-item>
          <el-form-item label="商品库存" prop="number">
            <el-input v-model="addForm.number"></el-input>
          </el-form-item>
          <el-form-item label="商品权重" prop="weight">
            <el-input v-model="addForm.weight"></el-input>
          </el-form-item>
          <el-form-item label="商品权重" prop="weight">
            <el-cascader
                v-model="options.selectID"
                :options="options.data"
                :props="props"
                separator="  >  "
                clearable
                @change="changeSelect"
                style="width: 500px"
            />
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品静态属性" :name="1">
          <el-form-item :label="s.name" v-for="s in attrData.static" :key="s.id">
            <el-input v-model="s.val"></el-input>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品动态属性" :name="2">
          <el-form-item :label="d.name" v-for="d in attrData.dynamic" :key="d.id">
            <el-checkbox-group v-model="d.val">
              <el-checkbox :label="v" name="type" v-for="(v,i) in d.val" :key="i" border/>
            </el-checkbox-group>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品图片" :name="3">
          <el-upload
              v-model:file-list="fileList.data"
              :action="base.baseURI+base.upload_img"
              :on-success="handleSuccess"
              list-type="picture"
              :on-remove="handleRemove"
              :on-preview="handlePreview"
          >
            <el-button type="primary">上传图片</el-button>
          </el-upload>
        </el-tab-pane>
        <el-tab-pane label="商品内容" :name="4">
          <EditorComponent @onDataEvent="getDateEvent"></EditorComponent>
          <el-button type="primary" @click="addProduct">添加商品</el-button>
        </el-tab-pane>
      </el-form>
    </el-tabs>
  </el-card>

  <el-dialog title="图片预览" v-model="PreDialogVisible" width="50%">
    <img class="pre-images" :src="preImageSrc">
  </el-dialog>
</template>

<script setup>
import {ArrowRight} from "@element-plus/icons-vue";
import {onMounted, reactive, ref} from "vue";
import api from "@/api";
import {ElMessage} from "element-plus";
import base from "@/api/base";
import EditorComponent from "@/components/EditorComponent.vue";
import {useRouter} from "vue-router";

const addFormRef = ref(null)
const active = ref(0)
const addForm = reactive({
  name: '',
  price: '',
  number: '',
  weight: '',
  cid_one: null,
  cid_two: null,
  cid_three: null,
  pics:[],
  introduce:null,
  attr_static:[],
  attr_dynamic:[]
})
const addFormRules = {
  name: [
    {required: true, message: '请输入商品名称', trigger: 'blur'},
    {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
  ],
  price: [
    {required: true, message: '请输入商品价格', trigger: 'blur'},
    {min: 0, max: 10, message: '长度在 0 到 10 个字符', trigger: 'blur'}
  ]
}
const options = reactive({
  data: [],
  selectID: null
})
const props = {
  value: 'id',
  label: 'name',
  expandTrigger: 'hover',
}
const attrData = reactive({
  static: [],
  dynamic: []
})
const fileList = reactive({
  data: []
})
const PreDialogVisible = ref(false)
let preImageSrc = ref('')
const router = useRouter()

onMounted(() => {
  get_category()
})
const changeSelect = () => {
  if (options.selectID) {
    if (options.selectID.length === 3) {
      addForm.cid_one = options.selectID[0]
      addForm.cid_two = options.selectID[1]
      addForm.cid_three = options.selectID[2]
    }
  }
}
// 获取商品分类

const get_category = () => {
  api.get_category(3).then(res => {
    options.data = res.data.data
  })
}

const getAttr = (s_key, s_type) => {
  if (s_type === 'static') {
    api.get_attr_by_category(s_key, s_type).then(res => {
      attrData.static = res.data.data
    })
  } else if (s_type === 'dynamic') {
    api.get_attr_by_category(s_key, s_type).then(res => {
      res.data.data.forEach(item => {
        item.val = item.val ? item.val.split(',') : []
      })
      attrData.dynamic = res.data.data
    })
  }
}

const beforeLeave = (activeName, oldActiveName) => {
  if (options.selectID) {
    if (options.selectID.length === 3) {
      //获取静态属性
      getAttr(options.selectID[2], 'static')
      getAttr(options.selectID[2], 'dynamic')
      return true
    }
  }
  ElMessage({
    message: '请选择商品分类',
    type: 'warning',
  })
  return false
}

const handleSuccess = (response,uploadFile,uploadFiles) =>{
  if(response.status===200){
    ElMessage({
      message: response.msg,
      type: 'success',
    })
    //将图片地址添加到addForm中
    addForm.pics.push(response.data)
  }else{
    ElMessage({
      message: response.msg,
      type: 'warning',
    })
  }
}

const handleRemove = (uploadFile,uploadFiles) =>{
  //要删除的图片的名称
  let removePath = uploadFile.response.data.path
  // 从addForm.pics中删除图片名称
  addForm.pics.splice(addForm.pics.path.indexOf(removePath),1)
}

const handlePreview = (uploadFile)=>{
  preImageSrc.value = uploadFile.response.data.url
  PreDialogVisible.value = true
}

const getDateEvent = (data)=>{
  addForm.introduce = data
}

const addProduct = () =>{
  addForm.attr_static = attrData.static
  addForm.attr_dynamic = attrData.dynamic
  console.log(addForm)
  api.add_product(addForm).then(res => {
    if (res.data.status === 200) {
      ElMessage({
        message: res.data.msg,
        type: 'success',
      })
      //跳转到商品列表页面
      router.push('/product_list')
    } else {
      ElMessage({
        message: res.data.msg,
      })
    }
  })
}
</script>

<style scoped>
.box-card {
  margin-top: 20px
}

.el-tabs {
  margin-top: 20px;
}
.pre-images{
  width: 100%;
}
</style>